package com.xxgc.qinglian.qinglianserver.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxgc.qinglian.qinglianserver.entity.ProjectEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class VoteWebSocketHandler extends TextWebSocketHandler {

    private final ObjectMapper objectMapper = new ObjectMapper();
    // 存储用户ID与WebSocketSession的映射（线程安全）
    private final Map<Integer, WebSocketSession> userSessionMap = new ConcurrentHashMap<>();
    // 存储所有活跃会话（用于广播）
    private final Map<Integer, WebSocketSession> activeSessions = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        // 从Principal中获取用户ID
        Integer userId = Integer.valueOf(session.getPrincipal().getName());
        System.out.println("WebSocket连接建立，用户ID: " + userId);

        // 存储用户ID与Session的映射
        userSessionMap.put(userId, session);
        activeSessions.put(userId, session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        // 处理客户端消息（如果需要）
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        // 移除用户ID与Session的映射
        Integer userId = Integer.valueOf(session.getPrincipal().getName());
        userSessionMap.remove(userId);
        activeSessions.remove(userId);
        System.out.println("WebSocket连接关闭，用户ID: " + userId);
    }

    // 向指定用户发送消息（剩余票数更新）
    public void sendMessageToUser(Integer userId, Map<String, Object> data) {
        WebSocketSession session = userSessionMap.get(userId);
        if (session != null && session.isOpen()) {
            try {
                String json = objectMapper.writeValueAsString(data);
                session.sendMessage(new TextMessage(json));
            } catch (IOException e) {
                System.err.println("发送消息失败: " + e.getMessage());
            }
        }
    }

    // 广播消息给所有用户（项目票数更新）
    public void broadcastMessage(Map<String, Object> data) {
        try {
            String json = objectMapper.writeValueAsString(data);
            TextMessage message = new TextMessage(json);

            for (WebSocketSession session : activeSessions.values()) {
                if (session.isOpen()) {
                    session.sendMessage(message);
                }
            }
        } catch (IOException e) {
            System.err.println("广播消息失败: " + e.getMessage());
        }
    }
}